/**
 * Created by admin on 2017/6/22.
 */
//web框架
var express = require('express');
// 静态文件服务中间件
var serveStatic = require('serve-static');
//文件路径
var path = require('path');
var utils = require('./utils');
var open = require('open');

module.exports = function (dir) {
    dir = dir || '.';

    //初始化Express
    var app = express();
    var router = express.Router();
    app.use('/assets', serveStatic(path.resolve(dir, 'assets')));
    app.use(router);

    //渲染文章
    router.get('/posts/*', function (req, res, next) {
        var name = utils.stripExtname(req.params[0]);
        var file = path.resolve(dir, '_posts', name + '.md');
        var html = utils.renderPost(dir, file);
        res.end(html);
    });

    //渲染列表
    router.get('/', function (req, res, next) {
        var html = utils.renderIndex(dir);
        res.end(html);

    });

    //app.listen(3000);
    var config = utils.loadConfig(dir);
    var port = config.port || 3000;
    var url = 'http://localhost:' + port;
    app.listen(port);
    open(url);
};

